#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>

#define NUM 5
typedef void(*fun_t)();
fun_t tasks[NUM];
////////////////////////任务////////////////////////////
void printLog()
{
    printf("this is a log print task\n");
}

void printNet()
{
    printf("this is a net task\n");
}

void printNPC()
{
    printf("this is a flush NPC\n");
}

void initTask()
{
    tasks[0]=printLog;
    tasks[1]=printNet;
    tasks[2]=printNPC;
    tasks[3]=NULL;
}

void excuteTask()
{
    for(int i=0;tasks[i];i++) tasks[i]();
}

int main()
{
    //int a=10;
    pid_t id = fork();
    if(id==0)
    {
        //child
        int cnt=10;
        while(cnt)
        {
            printf("I am child process,pid:%d,ppid:%d,cnt:%d\n",getpid(),getppid(),cnt);
            cnt--;
            sleep(1);
           //a/=0;
           // int *p=NULL;
            //*p=100;
    
        }
        sleep(1);
        exit(0);
    }

    int status=0;
    while(1)
    {
        pid_t rid= waitpid(id,&status,WNOHANG);
        if(rid>0)
        {
            printf("wait success,rid:%d,status:%d,exit code:%d\n",rid,status,WEXITSTATUS(status));
            break;
        }
        else if(rid==0)
        {
            printf("father say:child is running,do other thing\n");
            printf("################################### task begin#####################################\n");
            excuteTask();
            printf("################################### task end  #####################################\n");
        }
        else
        {
            perror("waitpid");
            break;
        }
        sleep(1);
    }

   // int status=0;
   // pid_t rid = waitpid(id,&status,0);
   // if(rid>0)
   // {
   //     //status
   //     //printf("wait success,rid:%d,status:%d,exit signo:%d,exit code:%d\n",rid ,status,status &0x7F,(status>>8)&0xFF);
   // 

   //     if(WIFEXITED(status))
   //     {
   //         printf("wait success,rid:%d,status:%d,exit code:%d\n",rid,status,WEXITSTATUS(status));
   //     }
   //     else{
   //         printf("child process error\n");
   //     }
   // }
    return 0;
}
